package com.geekgo.core.generator.plugin;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

/**
 * @author HeHaoyang
 * @version 2016/6/24 14:29
 */
public class SerializablePlugin extends PluginAdapter {

    private FullyQualifiedJavaType serializable;

    public SerializablePlugin() {
        super();
        serializable = new FullyQualifiedJavaType("java.io.Serializable");
    }

    @Override
    public boolean validate(List<String> list) {
        return true;
    }

    @Override
    public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass,introspectedTable);
        return true;
    }

    @Override
    public boolean modelPrimaryKeyClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass,introspectedTable);
        return true;
    }

    @Override
    public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        makeSerializable(topLevelClass,introspectedTable);
        return true;
    }

    protected void makeSerializable(TopLevelClass topLevelClass,IntrospectedTable introspectedTable){
        FullyQualifiedJavaType superClass = topLevelClass.getSuperClass();
        if (superClass!=null){
            String superName = superClass.getFullyQualifiedName();
            if ("".equals(superName.trim())){
                topLevelClass.addImportedType(serializable);
                topLevelClass.addSuperInterface(serializable);
            }
        }else{
            topLevelClass.addImportedType(serializable);
            topLevelClass.addSuperInterface(serializable);
        }
        topLevelClass.addAnnotation("@SuppressWarnings(\"serial\")");
    }
}
